package com.brother.realtime;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.log4j.Logger;

import com.brother.database.DataBase;
import com.brother.service.TrackerService;

public class MileageUpdator {
private final List<String> trackers = new CopyOnWriteArrayList<String>();
private Logger log = Logger.getLogger(MileageUpdator.class);

private static MileageUpdator instance;
public static MileageUpdator getInstance(){
	if(instance == null){
		instance = new MileageUpdator();
	}
	return instance;
}

private MileageUpdator(){
	
}

private TrackerService trackerSrv = new TrackerService();

public void addTask(String trackerId){
	if(!trackers.contains(trackerId)){
		trackers.add(trackerId);
	}
}

public void start(){
	new Thread(){
		public void run(){
			while(true){
				if(trackers.size() > 0){
					String trackerId = trackers.remove(0);
					log.debug("calculating mileage for tracker "+trackerId);
					try{
						trackerSrv.updateMileage(trackerId);
					}catch(Exception e){
						log.error("erro when caculating mileaage for "+trackerId, e);
					}
					DataBase.closeThreadConnection();
				}
				try {
					Thread.sleep(45000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}.start();
}

}
